package org.bulldog.playlist.program;

import org.bulldog.playlist.PlayListBuilder;
import org.bulldog.playlist.util.DateUtil;

import java.util.*;

/**
 * 插播播表生成器
 * Created by zhanghongbin on 2017/9/7.
 *
 * @author zhanghongbin
 * @version 1.0
 */
final class SpotsPlayListBuilder implements PlayListBuilder<List<Program>, Program> {

    private static final int DELAYED = 2;


    private List<Program> spotsDailyProgramList;

    public SpotsPlayListBuilder(List<Program> spotsDailyProgramList) {
        this.spotsDailyProgramList = spotsDailyProgramList;
    }

    /**
     * @param programList
     * @return
     */
    @Override
    public List<Program> build(List<Program> programList) {
        String currentTime = DateUtil.now();
        String currentDate = currentTime.split(" ")[0] + " ";
        List<Program> spotsProgramList = new ArrayList<>();
        for (Program program : programList) {
            try {
                String startTime = currentDate + program.getStartTime();
                String endTime = currentDate + program.getEndTime();
                int n = DateUtil.minus(currentTime, endTime);
                if (n < DateUtil.MIN_PLAY_DURATION) {
                    continue;
                }
                int startIndex = DateUtil.compare(currentTime, startTime);
                program.setStartTime(startTime);
                program.setEndTime(endTime);
                program.setLevel(1);
                program.setDuration(DateUtil.minus(startTime, endTime));
                if (startIndex == 1 && n >= 0) {
                    program.setPlayDuration(n + DELAYED);
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            spotsProgramList.add(program);
        }
        if (!spotsProgramList.isEmpty()) {
            spotsProgramList.addAll(this.spotsDailyProgramList);
            Collections.sort(spotsProgramList, ProgramAscendingOrder.ASCENDING_ORDER);
        } else {
            spotsProgramList.addAll(this.spotsDailyProgramList);
        }
        this.spotsDailyProgramList.clear();
        return spotsProgramList;
    }


}
